<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Approval;
use App\Models\ApprovalFlow;
use App\Models\ApprovalNode;
use App\Models\ApprovalRecord;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ApprovalService
{
    public function get($model)
    {
        $sql = Approval::when($model, function ($query, $model) {
            return $query->where('model',$model);
        });
        return $sql;
    }

    public function wait($model,$adminid)
    {
        $sql = Approval::with('created_user')->with('project')->where('status','afoot')->when($model, function ($query, $model) {
            return $query->where('model',$model);
        });
        // if($adminid > 0){
        //     $sql->where('admin_id',$adminid);
        // }
        return $sql;
    }

    public function launch($input){
        //判断是哪个流程
        $flow = ApprovalFlow::where('company_id',$input['company_id'])->where('model',$input['model'])->first();
        if(empty($flow)){
            throw new InvalidRequestException('未设置审批流程');
        }
        //查询审批节点
        $node = ApprovalNode::where('flow_id',$flow->id)->orderBy('id','asc')->get();
        if($node->isEmpty()){
            throw new InvalidRequestException('未设置审批节点未设置');
        }
        try {
            $data = DB::transaction(function () use ($input,$node) {
                $input['flow_id'] = $node[0]->flow_id;
                $input['created_at'] = Date("Y-m-d H:i:s",time());
                $data = Approval::create($input);
                $insert = [];
                foreach ($node as $k => $v) {
                    $arr = [];
                    $arr['company_id'] = $input['company_id'];
                    $arr['approval_id'] = $data->id;
                    $arr['node_id'] = $v->id;
                    $arr['admin_id'] = $v->admin_id;
                    $arr['role_id'] = $v->role_id;
                    $arr['result'] = 'afoot';
                    $arr['comment'] = '';
                    $arr['trans_to'] = 0;
                    $arr['level'] = $k + 1;
                    $arr['processed_at'] = Date("Y-m-d H:i:s",time());
                    $arr['files'] = '';
                    $insert[] = $arr;
                }
                ApprovalRecord::insert($insert);
                $ApprovalRecord = ApprovalRecord::where('approval_id',$data->id)->orderBy('id','asc')->first();
                $Approval = Approval::find($data->id);
                $Approval->role_id = $ApprovalRecord->role_id;
                $Approval->admin_id = $ApprovalRecord->admin_id;
                $Approval->current_record_id = $ApprovalRecord->id;
                $Approval->current_node_id = $ApprovalRecord->node_id;
                $Approval->level_count = count($insert);
                $Approval->save();
                return $data;
            });

            return $data;

        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function review($input){
        $Approval = Approval::find($input['approval_id']);
        if(empty($Approval)){
            throw new InvalidRequestException('未发起审批');
        }

        if($Approval->status == 'approved'){
            throw new InvalidRequestException('已通过，请勿重复提交');
        }
        if($Approval->status == 'rejected'){
            throw new InvalidRequestException('已驳回，请撤销后重新提交');
        }

        $record = ApprovalRecord::find($Approval->current_record_id);
        //是否到这个角色
        if($record->role_id != $input['role_id']){
            // throw new InvalidRequestException('审批角色错误,没有权限进行审批');
        }
        //是否到这个人
        if($record->admin_id != 0 && $record->admin_id != $input['admin_id']){
            // throw new InvalidRequestException('审批人错误,没有权限进行审批');
        }
        // 审批状态：afoot-审批中 approved-已通过 rejected-已驳回'
        try {
            $data = DB::transaction(function () use ($Approval,$input,$record) {
                $date = Date("Y-m-d H:i:s",time());
                $end = false;

                $record->result = $input['result'];
                $record->comment = $input['comment'] ?? '';
                $record->processed_at = $date;
                $record->save();
                //到下一级
                $next = ApprovalRecord::where('approval_id',$Approval->id)->where('result','afoot')->where('level',$record->level + 1)->first();
                if($next){
                    $Approval->current_node_id = $next->node_id;
                    $Approval->current_record_id = $next->id;
                    $Approval->role_id = $next->role_id;
                    $Approval->admin_id = $next->admin_id;
                }

                if($input['result'] == 'rejected'){
                    $Approval->rejected_at = $date;
                }
                if($input['result'] == 'approved' && ($Approval->level_count == $record->level)){
                    //判断是否最后一级
                    $end = true;
                    $Approval->approved_at = $date;
                    $Approval->status = 'approved';
                }

                $Approval->save();
                if($end && $Approval->model == 'Purchase'){
                    $WarehouseService = new WarehouseService();
                    $WarehouseService->insertIn($Approval->source_id);
                }
                //判断最终审批是否通过
                return $record;
            });

            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}